//
//  NSString+RCExpand.m
//  NSDate
//
//  Created by 杨晓辉 on 2017/7/20.
//  Copyright © 2017年 杨晓辉. All rights reserved.
//

#import "NSString+RCExpand.h"
#import <CommonCrypto/CommonCrypto.h>


@implementation NSString (RCExpand)
#pragma mark ---正则表达式验证--

/**
 验证邮箱是否正确

 @return 返回验证的结果
 */
-(BOOL)isCorrentEmail
{
    
    NSString * emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [test evaluateWithObject:self];
    
}
/**
 验证手机号是否正确

 @return 返回验证的结果
 */
- (BOOL)isCorrentMobile
{
    
        NSString *phoneRegex = @"^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])\\d{8}$";
        NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
        return [test evaluateWithObject:self];
}

/**
 验证车牌号是否正确

 @return 返回验证的结果
 */

- (BOOL)isCorrentCarNo
{
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", carRegex];
    return [test evaluateWithObject:self];
    
}
/**
 验证用户昵称是否正确(只能含有汉字英文和数字)
 
 @return 返回验证的结果
 */
- (BOOL)isCorrentNickname
{
    
    NSString *nicknameRegex = @"^[A-Za-z0-9\\u4e00-\\u9fa5]+$";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nicknameRegex];
    return [test evaluateWithObject:self];
}


/**
 验证密码是否有效（以字母开头,只能包含“字母”,“数字”,“下划线”,长度6~18）

 @return 返回验证的结果
 */
- (BOOL)isCorrentPassword
{
    
    NSString *passWordRegex = @"^([a-zA-Z]|[a-zA-Z0-9_]|[0-9]){6,18}$";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", passWordRegex];
    return [test evaluateWithObject:self];
}


- (BOOL)isCorrentSpecialCharacterPassword
{
    return YES;
}
/**
 验证身份证号是否正确

 @return 返回验证的结果
 */
- (BOOL)isCorrentIdentityCard
{
    
    NSString *identityCardRegex = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", identityCardRegex];
    return [test evaluateWithObject:self];
}
- (BOOL)isCorrentChinese 
{
   
    NSString *chineseRegex = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", chineseRegex];
    return [test evaluateWithObject:self];
}

/**
 验证ip地址

 @return 返回验证结果
 */
- (BOOL)isCorrentIPAddress
{
    NSString *iPRegex =  @"\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", iPRegex];
    return [test evaluateWithObject:self];
}
/**
 判断字符串中是否包含中文
 
 @return 返回结果（YES：包含）
 */
- (BOOL)isContainChinese
{
    NSUInteger length = [self length];
    for (NSUInteger i = 0; i < length; i++)
    {
        NSRange range = NSMakeRange(i, 1);
        NSString *subString = [self substringWithRange:range];
        const char *cString = [subString UTF8String];
        if (strlen(cString) == 3)
        {
            return YES;
        }
    }
    return NO;
}
#pragma mark ---文件路径--

#pragma mark ---字符串截取--
/**
 字符串截取从某个字符到某个字符之间的字符
 @param startString 开始截取的字符
 @param endString 结束的字符
 @return 返回截取结果
 */
- (NSString*)substringFrom:(NSString *)startString to:(NSString *)endString
{
    NSRange startRange = [self rangeOfString:startString];
    NSRange endRange = [self rangeOfString:endString];
    // 如果开始字符或或者结束字符在字符串中不存在 则不截取
    if (startRange.length==0||endRange.length==0) {
        return self;
    }
    NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
    
    return [self substringWithRange:range];
}
/**
 过滤字符串
 
 @param characterString 过滤字符
 @return 返回过滤的结果
 */
- (NSString*)filterCharacter:(NSString*)characterString
{
    
//    
//    NSString *b = [@"#####! 2 Z c c" stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"#!"]];
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:characterString];
    NSString *trimmedString = [self stringByTrimmingCharactersInSet:set];
    return trimmedString;
}

/**
 除去字符串开头和末尾的空格
 
 @return  返回处理的结果
 */
- (NSString *)trim
{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

/**
 清除HTML标签
 
 @return 返回去除标签的字符串
 */
- (NSString *)stringByStrippingHTML
{
    NSString *strippingStr = [self stringByReplacingOccurrencesOfString:@"<[^>]+>" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, self.length)];
    
    return strippingStr;
}
/**
 字符串反转
 @return 反转之后的字符串
 */
- (NSString*)reverseWords
{
    NSMutableString * reverStr = [NSMutableString stringWithCapacity:self.length];
    
    [self enumerateSubstringsInRange:NSMakeRange(0, self.length) options:NSStringEnumerationReverse|NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
        [reverStr appendString:substring];
    }];
    return reverStr;
}
/**
 阿拉伯数字转成中文
 @return 返回的中文数字
 */
- (NSString *)arebicTranslationToChinese;
{
    NSString *str = self;
    NSArray *arabic_numerals = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"];
    NSArray *chinese_numerals = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零"];
    NSArray *digits = @[@"个",@"十",@"百",@"千",@"万",@"十",@"百",@"千",@"亿",@"十",@"百",@"千",@"兆"];
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:chinese_numerals forKeys:arabic_numerals];
    
    NSMutableArray *sums = [NSMutableArray array];
    for (int i = 0; i < str.length; i ++) {
        NSString *substr = [str substringWithRange:NSMakeRange(i, 1)];
//        检验每个字符是否为阿拉伯数字 不是阿拉伯数字 返回原来的字符串;
        if (![arabic_numerals containsObject:substr]) {
            return self;
        }
        
        NSString *a = [dictionary objectForKey:substr];
        NSString *b = digits[str.length -i-1];
        NSString *sum = [a stringByAppendingString:b];
        if ([a isEqualToString:chinese_numerals[9]])
        {
            if([b isEqualToString:digits[4]] || [b isEqualToString:digits[8]])
            {
                sum = b;
                if ([[sums lastObject] isEqualToString:chinese_numerals[9]])
                {
                    [sums removeLastObject];
                }
            }else
            {
                sum = chinese_numerals[9];
            }
            
            if ([[sums lastObject] isEqualToString:sum])
            {
                continue;
            }
        }
        
        [sums addObject:sum];
    }
    
    NSString *sumStr = [sums componentsJoinedByString:@""];
    NSString *chinese = [sumStr substringToIndex:sumStr.length-1];
    NSLog(@"%@",str);
    NSLog(@"%@",chinese);
    return chinese;
}

/**
 获得汉字的拼音
 @return 得到汉字拼音
 */
- (NSString *)ChineseCharTranslationToPinyin
{
    //将NSString装换成NSMutableString
    NSMutableString *pinyin = [self mutableCopy];
    //将汉字转换为拼音(带音标)
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    NSLog(@"%@", pinyin);
    //去掉拼音的音标
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    NSLog(@"%@", pinyin);
    //返回最近结果
    return pinyin;
}



/** 获取字节数量 */
- (int)bytesCount
{
    NSInteger n = self.length;
    int i;
    int l = 0, a = 0, b = 0;
    unichar c;
    
    for (i = 0; i < n; i++)
    {
        c = [self characterAtIndex:i];
        if (isblank(c))
        {
            b++;
        }
        else if (isascii(c))
        {
            a++;
        }
        else
        {
            l++;
        }
    }
    
    if (a == 0 && l == 0)
    {
        return 0;
    }
    return l + (int)ceilf((float)(a + b) / 2.0);
}
/**
 获取字符串的高度
 @param font 文字的字号大小
 @param maxWidth 显示宽度
 @return 返回得到的高度
 */
- (CGFloat)stringGetHeightWithfont:(CGFloat)font maxWidth:(CGFloat)maxWidth
{
    
    NSDictionary * attribute = @{NSFontAttributeName:[UIFont systemFontOfSize:font]};
    NSStringDrawingOptions option = (NSStringDrawingOptions)(NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading);
    CGSize size = [self boundingRectWithSize:CGSizeMake(maxWidth, MAXFLOAT) options:option attributes:attribute context:nil].size;
    return size.height;
}

/**
 获取字符串的宽度
 
 @param font 文字的字号大小
 @return 返回得到的高度
 */
- (CGFloat)stringGetWidthWithFont:(CGFloat)font
{
    
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:font]};
    NSStringDrawingOptions option = (NSStringDrawingOptions)(NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading);
    
    CGSize size = [self boundingRectWithSize:CGSizeMake(1000, MAXFLOAT) options:option attributes:attribute context:nil].size;
    
    return size.width;
}

/**
 将数组和字典转换成JOSN字符串
 
 @param obj 需要转换的对象
 @return 返回json字符串
 */
+ (NSString*)jsonStingWithData:(id)obj
{
    NSError*error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:&error];
    NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return json;
}


#pragma mark ---加密--

-(NSString*) md5
{
    const char * cStrValue = [self UTF8String];
    unsigned char theResult[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStrValue, (CC_LONG)strlen(cStrValue), theResult);
    
    return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            theResult[0], theResult[1], theResult[2], theResult[3],
            theResult[4], theResult[5], theResult[6], theResult[7],
            theResult[8], theResult[9], theResult[10], theResult[11],
            theResult[12], theResult[13], theResult[14], theResult[15]];
}

- (NSString*) sha1
{
    const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:self.length];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_LONG len=(unsigned int) data.length;
    CC_SHA1(data.bytes, len, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return output;
}


/**
 哈希算法（256）
 
 @return 返回结果
 */
- (NSString *) sha256
{
    const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:self.length];
    
    uint8_t digest[CC_SHA256_DIGEST_LENGTH];
    CC_LONG len=(unsigned int) data.length;
    CC_SHA256(data.bytes, len, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return output;
}


/**
 base64加密
 
 @return 返回加密后的字符串
 */
-(NSString*)encodeBase64String
{
    
    NSData *nsdata = [self
                      dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString *base64Encoded = [nsdata base64EncodedStringWithOptions:0];

    return base64Encoded;
}
/**
 base64解密
 
 @return 返回解密结果
 */
-(NSString*)decodeBase64String
{
    NSData *nsdataFromBase64String = [[NSData alloc]
                                      initWithBase64EncodedString:self options:0];

    NSString *base64Decoded = [[NSString alloc]
                               initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];
    return base64Decoded;
}

@end
